import Vue from "vue"
import Router from 'vue-router'
import Home from '@/views/Home'
import Login from '@/views/Login'
import Search from '@/views/Search/index.vue'
import Register from '@/views/Register'
import Detail from '@/views/Detail/index.vue'
import AddCart from "@/views/AddCartSuccess/index.vue"
import ShopCart from "@/views/ShopCart/index.vue"
import  Trade from "@/views/Trade/index.vue"
import Pay  from  '@/views/Pay/index.vue'
import Center from '@/views/Center/index.vue'
//引入2集路由组件
import MyOrder from  '@/views/Center/myOrder'
import GroupOrder from  '@/views/Center/groupOrder'
Vue.use(Router)
import store from "@/store"
//需要重写VueRouter.prototype原型对象身上的push|replace方法
//先把VueRouter.prototype身上的push|replace方法进行保存一份
let originPush = Router.prototype.push;
let originReplace = Router.prototype.replace;
//重写VueRouter.prototype身上的push方法了
Router.prototype.push = function(location, resolve, reject) {
  //第一个形参：路由跳转的配置对象（query|params）
  //第二个参数：undefined|箭头函数（成功的回调）
  //第三个参数:undefined|箭头函数（失败的回调）
  if (resolve && reject) {
    //push方法传递第二个参数|第三个参数（箭头函数）
    //originPush：利用call修改上下文，变为(路由组件.$router)这个对象，第二参数：配置对象、第三、第四个参数：成功和失败回调函数
    //  call与apply的区别call 用,隔开 apply方法执行,传递数组

    originPush.call(this, location, resolve, reject)
  } else {
    //push方法没有产地第二个参数|第三个参数
    originPush.call(this, location, () => {}, () => {})
  }
}
Router.prototype.replace = function(location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(this, location, () => {}, () => {})
  }
}

let router = new Router({
  routes: [{
      path: '/',
      redirect: '/home',

    },
    {
    path:'/pay',
    component:Pay,
    name:"Pay",
    beforeEnter:(to,from,next)=>{
      if(from.path=="/trade"){
        next();
      }else{
        next(false);
      }
    },
    meta: {
      show: true
    }
    },
    {
    path:'/trade',
    component:Trade,
    name:"trade",
    //路由独享守卫
    beforeEnter:(to,from,next)=>{
      if(from.path=="/shopcart"){
        next();
      }else{
        next(false);
      }
    },
    meta: {
      show: true
    }
    },
    {
      path: '/addcartsuccess',
      component: AddCart,
      name: "addcartsuccess",
      meta: {
        show: true
      }
    },
    {
      path: '/shopcart',
      component: ShopCart,

      meta: {
        show: true
      }
    },
    {
      path: '/home',
      component: Home,
      meta: {
        show: true
      }
    },
    {
      path: '/detail/:skuid',
      component: Detail,
      meta: {
        show: true
      }
    },
    {
      path:'/paysuccess',
      //路由懒加载
      component:()=> import ('@/views/PaySuccess/index.vue'),
      // beforeEnter:(to,from,next)=>{
      //   if(from.path=="/pay"){
      //     next();
      //   }else{
      //     next(false);
      //   }
      // },
    },
    {
      path:'/center',
      component:Center,
      meta: {
        show: true
      },
      children:[{
        path:'/',
        redirect:"/center/myorder"
      },
        {
          path:"myorder",
          component:MyOrder
        },
        {
          path:"grouporder",
          component:GroupOrder
        }
      ]
    },
    {
      path: '/search/:keyword?',
      component: Search,
      meta: {
        show: true
      },
      name: "search",
      //布尔值写法：params
      //props:true
      // 对象写法
      // props:{a:1,b:2}
      // 函数写法：可以params参数、query参数 通过props
      // props:($route)=>{
      // 	return {keyword:$route.params.keyword,k:$route.query.k}
      // }
    },
    {
      path: '/login',
      component: Login,
      meta: {
        show: false
      }
    },
    {
      path: '/register',
      component: Register,
      meta: {
        show: false
      }
    }
  ],
  scrollBehavior(to, from, savedPosition) {

    return {
      y: 0
    }
  }
})

//全局守卫前置守卫（在路由跳转之间进行判断）
router.beforeEach(async (to, from, next) => {
  //to 去哪个路由的信息
  //from 从哪来的
  //next：放行函数
  let token = store.state.user.token
  let userInfo = store.state.user.userInfo
  let name = userInfo.name
  if (token) {
    if (to.path == '/login') {
      next('/home') }
      
     else {
      if (name) {
        next()
      } else {
        try {
          await store.dispatch("user/getUserInfo");
          next()
        } catch (e) {
          //TODO handle the exception
          await store.dispatch("user/userLogout")
          next('/login')
        }
      }
    }
    } else {
      if(to.path.indexOf('/trade')!=-1 ||to.path.indexOf("/pay")!=-1||to.path.indexOf("/center")!=-1){
        next('/login?redirect='+to.path)
      }
      else{
        next()
        }
        
  }

})

export default router
